import $common from '@/common/js/common.js'
import $global from '@/common/js/global.js'

var userInfo;
var userKey = "UserInfo";

userInfo = $common.getStorage(userKey);

if(userInfo==undefined){
	userInfo = {}
	if(location.host.lastIndexOf('localhost')>-1){
		//userInfo = {"ID":"5525"};//5848
	}
	//userInfo = {"ID":"0011205"};
	//userInfo = {"ID":"5848"};
}else{
	//某些用户信息不存在时特殊处理
}
module.exports = {
	ID: (userInfo.ID ? userInfo.ID : ''),
	IsOauth:(userInfo.IsOauth==undefined ? 1 : userInfo.IsOauth),
	NickName:userInfo.NickName,
	Mobile:userInfo.Mobile,
	UnionId:userInfo.UnionId,
	AppID: userInfo.AppID,
	UserID: userInfo.UserID,
	HeadImgUrl:userInfo.HeadImgUrl,
	OpenID:userInfo.OpenID,
	UserType:userInfo.UserType,
	RoleType:userInfo.RoleType,
	DataArea:userInfo.DataArea,
	SpreadCode:userInfo.SpreadCode,
	userInfo:userInfo,
	setInfo:function (value) {
		this.ID = value.ID;
		this.UserID = value.UserID;
		this.HeadImgUrl = value.HeadImgUrl;
		this.UserType = value.UserType;
		this.RoleType = value.RoleType;
		this.NickName = value.NickName;
		this.AppID = value.AppID;
		this.OpenID = value.OpenID;
		this.SpreadCode = value.SpreadCode;
		this.Mobile = value.Mobile;
		this.UnionId = value.UnionId;
		this.userInfo = value;
		$common.setStorage(userKey,value);
    },
	getInfo:function () {
		return this.userInfo;
	},
	setMobile:function (vl) {
		userInfo.Mobile = vl;
	    this.setInfo(userInfo);
	},
	checkLogin:function(success,path,query){
		if(path!="/pages/oauth/oauth2"){
			if(this.ID=='' || this.ID==undefined){
				var ua= window.navigator.userAgent.toLowerCase();
				if( (ua.match(/MicroMessenger/i) == 'micromessenger') && (ua.match(/wxwork/i) == 'wxwork') ){
					var redirect_uri = window.location.href;
					redirect_uri = redirect_uri.substring(0,redirect_uri.lastIndexOf('index.html'));
					redirect_uri = redirect_uri + "index.html?v=1.0#/pages/oauth/oauth2";
					var url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + $global.appId + '&redirect_uri=' + redirect_uri + '&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
					location.href = url;
				}else{
					//其它客户端跳转到空页面
				    uni.redirectTo({ url: "../oauth/empty"});
				}
			}else{
				if(success) success(true);
			}
		}else{
			if(success) success(true);
		}
	},
	login:function(success,isGetUserInfo,loginInfo){
		//获取用户信息
		var th = this;
		uni.getProvider({
			service:"oauth",
			success:function(res){
				var provider = res.provider[0]; //获取平台类型
                //获取code
				uni.login({
					provider: provider,
					success: function (loginRes) {
						var toDB = function(infoRes,swanid){
							//获取用户信息成功
							var user = infoRes ? infoRes.userInfo : undefined;
							var spreadCode = $common.getStorage("SpreadCode");
							var ajaxOptions = {
								url: "WeiXin/GetWXAppUserInfo",
								loading:true,
								type:"post",
								contentType:"application/x-www-form-urlencoded",
								data: { 
									Provider:provider,
									AppID: $global.appId, 
									SpreadCode:(spreadCode==undefined ? "" : spreadCode),
									Code: loginRes.code,
									AnonymousCode:loginRes.anonymousCode,
									NickName:(user ? user.nickName : ""),
									HeadImgUrl:(user ? user.avatarUrl: ""),
									Gender:(user ? user.gender: ""),
									Country:(user ? user.country: ""),
									Province:(user ? user.province: ""),
									City:(user ? user.city: ""),
									EncryptedData:(infoRes ? encodeURIComponent(infoRes.encryptedData) : ""),
									IV:(infoRes ? encodeURIComponent(infoRes.iv) : "")
									//swanid:swanid,
								},
								success:function(res){
									if(res.flag==0 || res.flag==1000)
									{				
										th.setInfo(res.data);
										if(success) success(true);
									}else{
										if(success) success(false,true);
										$common.alert(res.message + ",请重新打开小程序");
									}
								}
							};
							$common.initAjax(ajaxOptions);
						}
						
						//获取用户信息
						if(isGetUserInfo==1){
							// #ifdef MP-BAIDU
							toDB(loginInfo.userInfo);
							// #endif
							
							// #ifndef MP-BAIDU
							//获取用户头像和昵称情况
							uni.getUserInfo({
								provider: provider,
								withCredentials:true,
								// #ifdef MP-WEIXIN
								lang:"zh_CN",
								// #endif
								success: function (infoRes) {
									toDB(infoRes);
								},
								fail:function(infoRes){					
									$common.alert("用户授权已被你关闭，请在设置中打开",function(){
										uni.openSetting({
										  success(res) {
										    console.log(res.authSetting)
										  }
										});
									});
									if(success) success(false);
								}
							});
							// #endif
						}else{
							//记录用户信息情况
							// #ifdef MP-BAIDU
							// swan.getSwanId({
							// 	success: (res)=> {
							// 		toDB(undefined,res.data.swanid);
							// 	}
							// });
							// #endif
							
							toDB();
						}
					},
					fail:function(res){
						console.log(res);
						if(success) success(false);
					}
				});
			},
			fail:function(res){
				console.log(res);
				if(success) success(false);
			}
		});
	},
	getMobile(res,success){
		//获取手机号
		if(res.detail.errMsg=="getPhoneNumber:ok"){
			// if(this.Mobile!=""){
			// 	if(success) success(this.Mobile);
			// 	return;
			// }
			//获取code
			uni.login({
				provider: "weixin",
				success: (loginRes)=>{
					$common.initAjax({
						url: "WeiXin/BindMobile",
						loading:true,
						type:"post",
						contentType:"application/x-www-form-urlencoded",
						data: { 
							AppID: $global.appId, 
							UserID: this.ID, 
							Code: loginRes.code,
							IV:encodeURIComponent(res.detail.iv),
							EncryptedData:encodeURIComponent(res.detail.encryptedData) //res.detail.encryptedData
						},
						success:(res)=>{
							if(res.flag==1000)
							{				
								//保存手机信息
								this.setMobile(res.data.Mobile);
								if(success) success(res.data.Mobile);
							}else{
								$common.alert(res.message);
							}
						}
					});
				}
			});
		}	
	},
	subscribeMsg(templateIDs,complete,insertDB,openSetting){
		if(this.ID==undefined) return;
		
		var th = this;
		var insertData = function(ids){
			//插入到订阅模板到数据库
			$common.initAjax({
				url: "UserService.ashx?m=SubscribeMsg_Insert",
				data:{ UserID: th.ID,TemplateIDs: ids },
				success:function(res){
					if(res.flag!=0){
						console.log(res.result);
					}
				}
			});	
		};
		
		//微信订阅消息
		// #ifdef MP-WEIXIN
		var isSuccess = false;
		wx.requestSubscribeMessage({
			tmplIds: templateIDs,  
			success(res) {  
				if(insertDB){
					var len = templateIDs.length;
					var ids = [];
					for (var i=0; i < len; i++) {
						if(res[templateIDs[i]]=='accept')
						{
							//同意订阅
							ids.push(templateIDs[i]);
						}
					}
					//插入到数据库
					if(ids.length>0) {
						isSuccess = true;
						insertData(ids.join(","));
					}
				}		
			},
			fail(res) {
				if(res.errCode=="20004"){
					if(openSetting){
						$common.alert("订阅消息已被你关闭，请在设置中打开",function(){
							uni.openSetting({
							  success(res) {
							    console.log(res.authSetting)
							  }
							});
						});
					}
				}
				console.log(res)
			},
			complete:function(){
				if(complete) complete(isSuccess);
			}
		});	
		// #endif
	},
	quit(){
		$common.removeStorage(userKey);
	}
}